<template>
  <div>
    <vxe-modal
        v-model="show" id="add" width="50%" :size="size" :position="{top: 100}"
        @close="closeForm()" @show="open" show-zoom="" resize="" transfer="" show-footer="">
      <!-- storage 将窗口拖动的状态保存到本地 remember 再次打开窗口时还原窗口状态-->
      <!--标题-->
      <template #title>
        <h3>创建字段</h3>
      </template>
      <!--主体-->
      <template #default>
        <el-form :size="size" ref="form" :model="form" class="form" :rules="rules" label-width="100px">
          <el-row :gutter="10">
            <!-- 字段类型 -->
            <el-col :span="12">
              <el-form-item prop="type">
                <template slot="label">
                  <span>字段类型 </span>
                  <el-tooltip content="表单类型，修改数据类型通过数据结构设置" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-select tabindex="1" style="width:100%" v-model="form.type" @change="selectType" filterable placeholder="请选择">
                  <el-option v-for="(item,i) in field" :key="i" :label="item.name" :value="item.type"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 可录入 -->
            <el-col :span="12">
              <el-form-item label="可录入" prop="post_status">
                <template slot="label">
                  <span>可录入 </span>
                  <el-tooltip content="增加/修改表单中是否显示" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-radio-group v-model="form.post_status">
                  <el-radio-button :label="1">录入数据</el-radio-button>
                  <el-radio-button :label="0">不录入数据</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- 字段标题 -->
            <el-col :span="12">
              <el-form-item label="字段标题" prop="title">
                <template slot="label">
                  <span>字段标题 </span>
                  <el-tooltip content="默认设置为表单的标题和表格的列名" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-input tabindex="5" v-model="form.title" clearable placeholder="字段中文描述"/>
              </el-form-item>
            </el-col>
            <!-- 字段名称 -->
            <el-col :span="12">
              <el-form-item prop="field">
                <template slot="label">
                  <span>字段名称 </span>
                  <el-tooltip content="默认设置为数据库表中的字段名称" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-input tabindex="7" v-model="form.field" clearable placeholder="字段英文名称"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- 创建字段 -->
            <el-col :span="12">
              <el-form-item prop="create_table_field">
                <template slot="label">
                  <span>创建字段 </span>
                  <el-tooltip content="创建数据库表中的字段" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-radio-group v-model="form.create_table_field">
                  <el-radio-button :label="1">创建字段</el-radio-button>
                  <el-radio-button :label="0">虚拟字段</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 所属表 -->
            <el-col :span="12">
              <el-form-item prop="belong_table">
                <template slot="label">
                  <span>所属表 </span>
                  <el-tooltip content="设置为虚拟字段后，可以设定此字段引用的是哪个表中的同名字段" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-select
                    :disabled="form.create_table_field != '0'" @focus="getTablesByMenuId" tabindex="11"
                    @change="setPostStatus" clearable v-model="form.belong_table" filterable placeholder="关联字段所属表（配置多表专属，其它勿设置）">
                  <el-option v-for="(item,i) in tableList" :key="i" :value="item.table_name">
                    {{ item.table_name }}({{ item.title }})
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- 数据结构 -->
            <el-col :span="12">
              <el-form-item prop="datatype">
                <template slot="label">
                  <span>数据类型 </span>
                  <el-tooltip content="创建的数据库中表的字段的数据类型" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-select tabindex="13" v-model="form.datatype" filterable @change="setFieldLength" placeholder="请选择">
                  <el-option v-for="(item,i) in propertyField" :key="i" :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 字段长度 -->
            <el-col :span="12">
              <el-form-item prop="length">
                <template slot="label">
                  <span>字段长度 </span>
                  <el-tooltip content="创建的数据库字段的长度" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-input tabindex="15" v-model="form.length" placeholder="字段长度"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- 约束类型 -->
            <el-col :span="12">
              <el-form-item prop="validate">
                <template slot="label">
                  <span>约束类型 </span>
                  <el-tooltip content="设置常见表单验证方式" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-checkbox-group v-model="form.validate" @change="checkDefault">
                  <el-checkbox-button label="notempty">非空</el-checkbox-button>
                  <el-checkbox-button label="unique">唯一</el-checkbox-button>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <!-- 字段索引 -->
            <el-col :span="12">
              <el-form-item prop="indexdata">
                <template slot="label">
                  <span>字段索引 </span>
                  <el-tooltip content="为此字段创建索引" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-select tabindex="19" v-model="form.indexdata" filterable placeholder="请选择">
                  <el-option key="1" label="普通索引" value="index"></el-option>
                  <el-option key="2" label="唯一索引" value="unique"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- 默认值 -->
            <el-col :span="12">
              <el-form-item prop="default_value">
                <template slot="label">
                  <span>默认值 </span>
                  <el-tooltip content="同步数据表默认值" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-input tabindex="21" v-model="form.default_value" clearable placeholder="同步数据表默认值"/>
                <span class="form-desc">同步数据表默认值</span>
              </el-form-item>
            </el-col>
            <!-- 表单验证 -->
            <el-col :span="12">
              <el-row>
                <el-col :span="20">
                  <el-form-item prop="rule">
                    <template slot="label">
                      <span>表单验证 </span>
                      <el-tooltip content="验证规则的正则表达式，右侧下拉框可以选择预设规则" placement="top-start">
                        <i class="el-icon-warning-outline"></i>
                      </el-tooltip>
                    </template>
                    <template slot="default">
                      <el-row :gutter="5">
                        <el-col :span="15">
                          <el-input tabindex="23" v-model="form.rule" placeholder="输入框验证规则"/>
                        </el-col>
                        <el-col :span="8">
                          <el-select tabindex="25" :size="size" v-model="default_rules" @change="setDefaultRule" prop="default_rules" clearable filterable placeholder="请选择">
                            <el-option v-for="(item,index) in ruleList" :key="index" :label="index" :value="item"></el-option>
                          </el-select>
                        </el-col>
                      </el-row>
                    </template>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <!-- 日期格式 -->
            <el-col :span="24" v-if="[9,11,12].indexOf(form.type) != -1">
              <el-form-item prop="datetime_config">
                <template slot="label">
                  <span>日期格式 </span>
                  <el-tooltip content="设置日期时间格式" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-radio-group :size="size" v-model="form.datetime_config">
                  <el-radio-button label="datetime">年月日时分秒</el-radio-button>
                  <el-radio-button label="date">年月日</el-radio-button>
                  <el-radio-button label="year">年</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="time">时分秒</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 层级 -->
            <el-col :span="24" v-if="form.type == 22">
              <el-form-item label="层级" prop="address_type">
                <template slot="label">
                  <span>层级 </span>
                  <el-tooltip content="设置省市区显示到哪一个级别" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-radio-group v-model="form.other_config.address_type">
                  <el-radio-button :label="1">省市区</el-radio-button>
                  <el-radio-button :label="2">省市</el-radio-button>
                  <el-radio-button :label="3">省</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 长度 -->
            <el-col :span="24" v-else-if="form.type == 31">
              <el-form-item label="长度" prop="rand_length">
                <template slot="label">
                  <span>长度 </span>
                  <el-tooltip content="设置随机数位数" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <el-input tabindex="31" v-model="form.other_config.rand_length" clearable placeholder="随机数长度"/>
              </el-form-item>
            </el-col>
            <!-- 选项配置 -->
            <el-col :span="24" v-if="list_item">
              <el-form-item label="选项配置" prop="item_config">
                <template slot="label">
                  <span>选项配置 </span>
                  <el-tooltip content="选择预设值或者点击追加自定义" placement="top-start">
                    <i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </template>
                <template slot="default">
                  <el-row v-for="(item,i) in form.item_config" :key="i">
                    <el-col :span="8">
                      <el-form-item class="activeItem">
                        <el-input tabindex="33" v-model="item.key" placeholder="选项名称"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item class="activeItem">
                        <el-input tabindex="35" style="position:relative;left:5px;" v-model="item.val" placeholder="选项值"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item class="activeItem">
                        <el-select tabindex="37" style="position:relative;left:10px;" v-model="item.label_color" size="small" clearable placeholder="请选择背景色">
                          <el-option key="1" style="background:#409eff" label="primary" value="primary"></el-option>
                          <el-option key="2" style="background:#67c23a" label="success" value="success"></el-option>
                          <el-option key="3" style="background:#909399" label="info" value="info"></el-option>
                          <el-option key="4" style="background:#e6a23c" label="warning" value="warning"></el-option>
                          <el-option key="5" style="background:#f56c6c" label="danger" value="danger"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="2">
                      <el-button tabindex="39" type="danger" size="mini" style="position:relative;left:15px" icon="el-icon-close" @click="deleteItem('item_config',i)"></el-button>
                    </el-col>
                  </el-row>
                  <div>
                    <el-button tabindex="41" type="success" icon="el-icon-plus" style="padding:5px 7px" :size="size" @click="addItem('item_config')">追加</el-button>
                    <el-button tabindex="43" v-if="form.item_config.length > 0" type="warning" icon="el-icon-delete" style="padding:5px 7px" :size="size" @click="clearItem('item_config')">清空</el-button>
                    <el-select tabindex="45" v-if="form.item_config.length === 0" :size="size" style="height:25px; light:25px; margin-left:20px;" v-model="default_config" @change="setDefaultItem" placeholder="请选择默认配置">
                      <el-option v-for="(item,i) in itemList" :key="i" :label="item.name" :value="item.item"></el-option>
                    </el-select>
                  </div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <!--底部-->
      <template #footer>
        <el-button :size="size" :loading="loading" type="primary" @click="submit">
          <span v-if="!loading">确 定</span><span v-else>提 交 中...</span>
        </el-button>
        <el-button :size="size" @click="closeForm">取 消</el-button>
      </template>
    </vxe-modal>
    <Icon :iconshow.sync="iconDialogStatus" :currentIconModel.sync="currentIconModel" @selectIcon="selectIcon"
          :size="size"></Icon>
  </div>
</template>
<script>
import {createField, getConfigList, getTablesByMenuId} from '../../sys'
import Icon from '@/components/common/Icon.vue'

export default {
  name: 'addField',
  components: {Icon},
  props: {
    show: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'small'
    },
    field: {
      type: Array,
    },
    itemList: {
      type: Array,
    },
    menu: {
      type: Object,
    }
  },
  data() {
    return {
      form: {
        post_status: '1',
        create_table_field: '1',
        list_show: '2',
        menu_id: this.$route.query.menu_id,
        validate: [],
        item_config: [],
        other_config: {
          address_type: '1',
        },
        datatype: '',
        length: '',
        belong_table: '',
      },
      iconDialogStatus: false,
      currentIconModel: '',
      activeName: 'first',
      list_item: false,
      loading: false,
      propertyField: [],
      default_config: '',
      default_rules: '',
      ruleList: [],
      tableList: [],
      rules: {
        title: [{required: true, message: '字段中文名不能为空', trigger: 'blur'}],
        field: [{required: true, message: '字段英文名不能为空', trigger: 'blur'}],
        type: [{required: true, message: '字段类型不能为空', trigger: 'blur'}],
        login_fields: [{required: true, message: '请配置登录账号密码字段', trigger: 'blur'}],
      },
    }
  },
  methods: {
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          this.form.menu_id = this.menu.menu_id
          createField(this.form).then(res => {
            if (res.status == 200) {
              this.$message({message: '操作成功', type: 'success'})
              this.$emit('refesh_list')
              this.closeForm()
            } else {
              this.loading = false
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    open() {
      getConfigList().then(res => {
        this.ruleList = res.ruleList
        this.propertyField = res.propertyField
      })
    },
    selectType() {
      this.field.forEach(item => {
        if (this.form.type == item.type) {
          this.propertyField.forEach(vo => {
            if (item.property == vo.type) {
              this.form.datatype = vo.name
              this.form.length = vo.decimal ? vo.maxlen + ',' + vo.decimal : vo.maxlen
            }
          })
          this.list_item = item.item
          if (!item.item) {
            this.form.item_config = []
          }
        }
      })
    },
    checkDefault(val){
      val.find((item)=>{
        if(item == 'unique'){
          if(this.form.default_value){
            this.$message({message: '已清空默认值设置', type: 'warning'})
            this.form.default_value = ''
          }
        }
      })
    },
    setDefaultValue() {
      this.form.config = this.default_config
    },
    setDefaultRule() {
      this.form.rule = this.default_rules
    },
    setFieldLength() {
      this.propertyField.forEach(item => {
        if (this.form.datatype == item.name) {
          this.form.length = item.decimal ? item.maxlen + ',' + item.decimal : item.maxlen
        }
      })
    },
    addItem(key) {
      this.form[key].push({})
    },
    deleteItem(key, index) {
      this.form[key].splice(index, 1)
    },
    clearItem(key) {
      this.form[key] = []
    },
    setDefaultItem(val) {
      this.form['item_config'] = val
    },
    iconOpen(model) {
      this.iconDialogStatus = true
      this.currentIconModel = model
    },
    selectIcon(icon) {
      this.form.other_config.pre_icon = icon
    },
    getTablesByMenuId() {
      getTablesByMenuId({menu_id: this.$route.query.menu_id}).then(res => {
        this.tableList = res.data
      })
    },
    setPostStatus() {
      this.form.post_status = '0'
    },
    closeForm() {
      this.$emit('update:show', false)
      this.loading = false
      this.$refs['form'].resetFields()
      this.$nextTick(() => {
        this.default_rules = ''
        this.list_item = false
        this.form.other_config = {}
        this.activeName = 'first'
      })
    }
  },
}
</script>
<style scoped>
.activeItem {
  margin-bottom: 3px
}

.el-checkbox-group li {
  float: left;
  margin-left: 10px;
  width: 150px;
  margin-top: 10px
}
</style>
